package com.server;

import java.util.ArrayList;
import java.util.List;

import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.player.Data;

import entities.hero.Hero;
import entities.spells.Spell;

public class GameServerListener extends Listener {
	
	private List<Connection> connections = new ArrayList<Connection>();
	private List<Hero> heroes = new ArrayList<Hero>();
	private int index = 0;
	private boolean ready = false;
	
	public GameServerListener() {
		
	}
	
	@Override
	public void received (Connection connection, Object object) {		
		if (object instanceof Hero) {
			if (index < 2) {
				System.out.println("Connection recieved");
				connections.add(connection);
				
				Hero hero = (Hero) object;
				heroes.add(hero);
				
				index++;
			} 
			
			if (index == 2) {
				ready = true;
				
				for (Connection c : connections) {
					c.sendTCP(c.getID());
				}
				
				connections.get(1).sendTCP(heroes.get(0));
				connections.get(0).sendTCP(heroes.get(1));
				
				for (Connection c : connections) {
					c.sendTCP(ready);
				}
			}
		}
		
		if (object instanceof Data) {
			Data position = (Data) object;
				
			if (connection.equals(connections.get(0))) {
				connections.get(1).sendUDP(position);
			} else {
				connections.get(0).sendUDP(position);
			}
		}
		
		if (object instanceof String) {
	    	String text = (String) object;
	    	
    		for (Connection c : connections) {
				c.sendTCP(text);
			}
	    }
		
		if (object instanceof Spell) {
			Spell spell = (Spell) object;
			
			if (connection.equals(connections.get(0))) {
				connections.get(1).sendUDP(spell);
			} else {
				connections.get(0).sendUDP(spell);
			}
		}
	}
}
